#pragma once

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "Log.hpp"
#include "Err.hpp"

const static int default_listenfd = -1;
const static int backlog = 32;
class sock
{
public:
    sock()
        :_listenfd(default_listenfd)
    {}
    ~sock()
    {
        close(_listenfd);
    }
    void Socket()
    {
        _listenfd = socket(AF_INET,SOCK_STREAM,0);
        if(_listenfd == default_listenfd)
        {
            LOG(FATAL,"socket error!");
            exit(SOCKET_ERR);
        }

        int val = 1;
        int n = setsockopt(_listenfd,SOL_SOCKET,SO_REUSEADDR,&val,sizeof(val));
        if(n == -1)
        {
            LOG(ERROR,"setsockopt -> SO_REUSEADDR error!");
        }
    }

    void Bind(short port)
    {
        sockaddr_in server;
        memset(&server,0,sizeof(server));
        server.sin_addr.s_addr = INADDR_ANY;
        server.sin_port = htons(port);
        server.sin_family = AF_INET;
        int n = bind(_listenfd,(sockaddr *)&server,sizeof(server));
        if(n == -1)
        {
            LOG(FATAL,"bind error!");
            exit(BIND_ERR);
        }
    }

    void Listen()
    {
        int n = listen(_listenfd,backlog);
        if(n == -1)
        {
            LOG(FATAL,"listen error!");
            exit(LISTEN_ERR);
        }
    }

    int get_fd()
    {
        return _listenfd;
    }

    int Accept()
    {
        sockaddr_in client;
        socklen_t len = sizeof(client);
        int connfd = accept(_listenfd,(sockaddr *)&client,&len);
        if(connfd == -1)
        {
            LOG(ERROR,"accept error!");
        }
        else 
        {
            LOG(NORMAL,"get a connfd: %d",connfd);
        }
        return connfd;
    }
protected:
    int _listenfd;
};